package com.ruoyi.base.redis.verifycode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 验证码
 *
 * @author lcf
 */
@Component
public class VerifyCodeRedis {

    @Autowired
    public StringRedisTemplate redisTemplate;

    /**
     * key前缀
     */
    private final String prefix = "verifyCode:";
    /**
     * 过期时间单位
     */
    private TimeUnit timeUnit = TimeUnit.MINUTES;
    /**
     * 过期时间
     */
    private int outTime = 2;

    /**
     * 删除缓存
     */
    public void delCache(String key) {
        redisTemplate.delete(getKey(key));
    }

    /**
     * 缓存
     */
    public void cache(String key, String code) {
        redisTemplate.boundValueOps(getKey(key)).set(code, outTime, timeUnit);
    }

    /**
     * 获取
     */
    public String getCache(String key) {
        return redisTemplate.boundValueOps(getKey(key)).get();
    }

    /**
     * 拼接key
     */
    private String getKey(String key) {
        return prefix + key;
    }
}
